package arconplugin.handlers;

import java.io.File;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.FileDialog;

import arconplugin.Activator;
import arconplugin.preferences.PreferenceConstants;

public class SetupArconHandler extends ArConBaseHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		LetUserSelectArconPath();
		return null;
	}

	/**
	 * Get the pre-set path or let the user select the path if it doesn't exist
	 * @return path or null if no correct path was given
	 */
	protected String GetArconPath() {
		String path = LoadArconPath();
		if(path==null) {
			path = LetUserSelectArconPath();
		}		
		return path;
	}
	
	/**
	 * Give the user a file dialog to select the ArCon executable.
	 * @return
	 */
	private String LetUserSelectArconPath() {
		//If ArCon wasn't found, open a FileDialog for the user to select it
		FileDialog fileDialog = new FileDialog(getShell()); //TODO: check shell and other calls for null
		String[] ext = {"*.exe"};
		fileDialog.setFilterExtensions(ext);
		fileDialog.setText("File dialog - Choose the ArCon file");
		String path = fileDialog.open();
		if (path != null) {//A check to see so that a file were chosen
			SaveArconPath(path);
		}
		return path;
	}
	
	/**
	 * Save the Arcon path.
	 * @param path
	 */
	private void SaveArconPath(String path) {
		IPreferenceStore store = Activator.getDefault().getPreferenceStore();
		store.setValue(PreferenceConstants.P_ARCON_PATH, path);
	}

	/**
	 * Load ArCon Path from plugin settings.
	 * @return path, null if no valid path was found
	 */
	private String LoadArconPath() {
		IPreferenceStore store = Activator.getDefault().getPreferenceStore();
		String path = store.getString(PreferenceConstants.P_ARCON_PATH);
        
		//A check to see if the file specified exist
		if (path!=null && (new File(path)).exists()) { 
			return path;
		}
		//failed to get a valid path
		return null;
	}
}
